<template>
  <div class="app-container">
    <div class="report-view">
      <el-row>
        <el-col :span="4">
          <div class="sidebar-t">
            统计报表
          </div>
          <Sidebar class="sidebar-container" />
        </el-col>
        <el-col :span="20">
          <div class="r-top">
            <span class="l">
              <el-switch
                v-model="form.unviewedOnly"
                class="switch unread"
                active-text="查看未读报表"
                inactive-text=""
                @change="handleFilterUnReadSwitch"
              />
            </span>
            <span class="r">
              <el-select
                v-model="form.dir"
                clearable
                placeholder="排序"
                @change="handleChangeSort"
              >
                <el-option
                  v-for="item in sortOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-date-picker
                v-model="dateRange"
                :editable="false"
                class="date-ranger"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleChangeDate"
              />
              <!-- <el-input class="kw"
						    placeholder="关键字"
						    suffix-icon="el-icon-search"
						    v-model="filter.keyword">
						  </el-input> -->
            </span>
          </div>
          <div
            v-infinite-scroll="loadMore"
            class="file-manage"
            infinite-scroll-disabled="busy"
            infinite-scroll-distance="0"
          >
            <div
              v-for="(item, index) in fileManage"
              v-if="isMoreData"
              :key="index+1"
              class="file-container"
              :label="item"
              :value="item"
            >
              <p class="t">
                <!--上传人：<span> {{ item.executor||'---' }} </span>-->
                <span> {{ item.startTime | filterYMD }} </span>---<span> {{ item.endTime | filterYMD }} </span>
              </p>
              <el-row>
                <el-col
                  v-show="item.records.length===0"
                  :span="4"
                >
                  <div class="file-item null">
                    <i class="el-icon-document" />
                    <p class="name" />
                    <em />
                  </div>
                </el-col>
                <el-col
                  v-for="(it, i) in item.records"
                  :key="i+1"
                  :v-if="item.records.length!==0"
                  :span="4"
                  :label="it"
                  :value="it"
                >
                  <div
                    :class="{'file-item': true,
                             'null': false,
                             'stat_case': [1].includes(it.type),
                             'hour': [2].includes(it.type),
                             'week_hour': [3].includes(it.type),
                             'last_week_hour': [4].includes(it.type),
                             'bill': [5].includes(it.type)
                    }"
                    @click="gotoReportDiagram(it)"
                  >
                    <i
                      class="el-icon-document"
                      :style="backgroundImg(it.path)"
                    />
                    <p class="name" />
                    <span class="scope">{{ ['小组', '部门', '机构'][it.scope] }}</span>
                    <em>{{ it.time | filterYMDHMS }}</em>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script type="text/javascript">

import { mapGetters } from 'vuex'
import { Sidebar } from '@/views/layout/components'
import { parseTime } from '@/utils'
// import { route_origins } from '@/api/routes'
import { reportViewList } from '@/api/statReport'
// import infiniteScroll from 'vue-infinite-scroll'

export default {
  name: 'ReportView',
  components: {
    Sidebar
  },
  // directives: {
  // 	infiniteScroll
  // },
  computed: {
    ...mapGetters([
      'stafftab',
      'skyReportCriteria'
    ])
    /* sidebar() {
			return this.$store.state.app.sidebar
		} */
  },
  filters: {
    filterYMD(date) {
      return date ? parseTime(date, '{y}-{m}-{d}') : ''
    },
    filterYMDHMS(date) {
      return date ? parseTime(date) : ''
    }
  },
  data() {
    return {
      isMoreData: true,
      isMoreScroll: true,
      sortOptions: [{
        value: 'asc',
        label: '时间正序'
      }, {
        value: 'desc',
        label: '时间倒序'
      }],
      fileManage: [],
      dateRange: '',
      formStep: 3,
      lastForm: '',
      form: {
        unviewedOnly: false,
        dir: '',
        startTime: '',
        endTime: '',
        offset: 0,
        limit: 3,
        category: '',
        type: ''
      },
      busy: false,
      skyReportRoute: localStorage.skyReportRoute ? JSON.parse(localStorage.skyReportRoute) : {},
      dirMap: {
        weekly: 'ReportViewWeek',
        daily: 'ReportViewDay',
        type: [0, 'StatCaseCover', 'ReportAvgEfficient', 'ReportAvgEfficientTeamWeek', 'ReportAvgEfficientTeamWeekDuring', 'CasePayBackReport', 'CaseCallReport'],
        reportType: [0, 'stat_case', 'hour', 'week_hour', 'last_week_hour', 'bill_payment']
      },
      isCreated: false
    }
  },
  created() {
    this.isCreated = true
    // console.warn('created-this.vuex.skyReportCriteria:', this.skyReportCriteria.obj)
    console.warn('created-localStorage:', localStorage.skyReportRoute)
    this.skyReportCriteria.obj.type = this.skyReportCriteria.obj.category = ''
    this.form.type = this.form.category = ''
    this.form.offset = this.skyReportCriteria.obj.offset = 0
    if (this.skyReportRoute.type) {
      this.form.type = this.skyReportCriteria.obj.type = this.skyReportRoute.type
    } else if (this.skyReportRoute.category) {
      this.form.category = this.skyReportCriteria.obj.category = this.skyReportRoute.category
    }
  },
  mounted() {
    this.routerView()
    console.error('this.form-Mounted:', this.form.category, this.form.type)
  },
  beforeDestroy() {
    this.form.offset = 0
    this.skyReportCriteria.obj = this.form
  },
  methods: {
    routerView() {
      const isCategory = typeof Object.values(this.skyReportRoute)[0] === 'string'
      const currParam = isCategory ? this.dirMap[Object.values(this.skyReportRoute)[0]] : this.dirMap.type[Object.values(this.skyReportRoute)[0]]
      console.warn('currParamcurrParam:', currParam, Object.keys(this.skyReportRoute))
      document.querySelectorAll('.current-sidebar .ico').forEach((m, i) => {
        m.className = m.className.replace(/\sactived/g, '')
        const classList = m.className.split(' ')
        // console.warn(localStorage.skyReportRoute, '|', currParam, '|', m.className, classList.includes(currParam))
        if (localStorage.skyReportRoute) {
          // if (new RegExp(currParam).test(m.className)) {
          if (classList.includes(currParam)) {
            m.className = `${m.className} actived`
          }
        }
      })
    },
    loadMore() {
      if (!this.isMoreScroll) {
        // app.style.height = he
        return
      }
      this.busy = true
      console.log('loading... ' + new Date())
      this.form.limit = this.formStep
      console.warn(window.scrollY, window.pageYOffset, window.screen.height, window.screen.availTop, window.innerHeight)
      this.getReportViewList()
      setTimeout(t => {
        const app = document.querySelector('.file-manage')
        const height = app && app.clientHeight || 0
        console.log('app.clientHeightapp.clientHeight:', app.clientHeight)
        app.style.height = height + 200 + 'px'
        console.log('end... ' + new Date())
        this.busy = false
        this.form.offset += 3
      }, 1000)
    },
    getReportViewList(isLoadMore) {
      this.isMoreScroll = false
      this.form.startTime = this.dateRange && this.dateRange[0] || ''
      this.form.endTime = this.dateRange && this.dateRange[1] || ''
      // this.form.category = this.skyReportRoute.category
      // this.form.type = this.skyReportRoute.type
      console.log('skyReportRoute:', this.skyReportRoute)

      if (this.lastForm === JSON.stringify(this.form)) return
      let postData = {}
      if (this.isCreated) {
        postData = this.skyReportCriteria.obj
        this.form.unviewedOnly = this.skyReportCriteria.obj.unviewedOnly || this.form.unviewedOnly
        this.form.dir = this.skyReportCriteria.obj.dir || this.form.dir
        this.form.startTime = this.skyReportCriteria.obj.startTime || this.form.startTime
        this.form.endTime = this.skyReportCriteria.obj.endTime || this.form.endTime
        // this.form.offset = this.skyReportCriteria.obj.offset || this.form.offset
        // this.form.limit = this.skyReportCriteria.obj.limit || this.form.limit
        // this.form.category = this.skyReportCriteria.obj.category || this.form.category
        // this.form.type = this.skyReportCriteria.obj.type || this.form.type
        if (this.form.startTime) {
          this.dateRange = [this.form.startTime, this.form.endTime]
        }
      } else {
        postData = this.form
      }
      reportViewList(postData).then(response => {
        console.log('getReportViewList:', response)
        console.log('this.fileManage:', this.fileManage)
        /* this.$message({
				    message: response && response.resultMsg || '获取所有报表成功！',
				    type: 'success'
				}) */
        if (response.resultCode === 204) {
          this.fileManage = [...this.fileManage, ...response.module]
          this.isCreated = false
          this.isMoreScroll = !!response.module.map(m => m.records.length).filter(n => n).length
          return
        }
        // !isLoadMore && (this.fileManage.length = 0)
        if (this.fileManage.length === [...this.fileManage, ...response].length) {
          this.isCreated = false
          this.isMoreData = false
          return
        }
        this.fileManage = [...this.fileManage, ...response]
        console.log('this.fileManage:', this.fileManage)
        this.lastForm = JSON.stringify(this.form)
        this.isCreated = false
      }).catch(err => {
        // this.isMoreScroll = true
        this.$message({
          message: err && err.resultMsg || '获取所有报表失败！',
          type: 'error'
        })
      })
    },
    handleFilterUnReadSwitch() {
      // console.log(this.form.unviewedOnly)
      this.isMoreScroll = true
      this.fileManage = []
      this.form.offset = 0
      this.getReportViewList()
    },
    handleChangeSort() {
      this.isMoreScroll = true
      this.fileManage = []
      this.form.offset = 0
      this.getReportViewList()
    },
    handleChangeDate() {
      this.isMoreScroll = true
      this.fileManage = []
      this.form.offset = 0
      this.getReportViewList()
    },
    fileImagePath(name) {
      if (!/\.(png|jpeg|jpg|gif|bmp)$/img.test(name)) {
        return 'https://static.afufintech.com/images/logo.png'
      }
      // return `${route_origins}file?path=${name}`
    },
    backgroundImg(path) {
      // if (!/\.(png|jpeg|jpg|gif|bmp)$/img.test(path)) {}
      // return `background-image:url(${route_origins}file?path=${path});background-size:auto 100%;color:transparent;`
    },
    gotoReportDiagram(it) {
      console.log('it;;', it)
      const _skyTrace = localStorage.skyTrace ? JSON.parse(localStorage.skyTrace) : {}
      localStorage.setItem('skyTrace', JSON.stringify(Object.assign(_skyTrace, {
        homeReportId: it.sid,
        scope: it.scope
      })))
      if (!it.type) return
      this.$router.push({
        path: `/statReport/${this.dirMap.reportType[it.type]}`
      })
    },
    openDocFile(path) {
      console.log('openDocFile')
      // window.open(`${route_origins}file?path=${path}`)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.app-container{
	overflow: hidden;
}
.report-view{
	.sidebar-t{
		background: #01011B;
		color: white;
		font-size: 16px;
		font-weight: bolder;
		text-align: center;
		padding: 21px 0;
	}
	// .scroll-container
	.sidebar-container{
		overflow: hidden;
		min-height: 500px;
		background: white !important;
	}
	.r-top{
		padding: 15px 0px 0 15px;
		.switch{
			&.unread{
				.el-switch__label *{
					font-size: 12px !important;
				}
			}
		}
		.r{
			float: right;
			.el-input{
				width: 160px;
			}
		}
		.el-date-editor{
			width: 300px;
    		border-radius: 0;
    		border-radius: 0;
			.el-range-separator{
				width: 20px;
			}
			.el-range__close-icon{ margin-top: -32px; }
		}
	}
	.file-manage{
		// background:white;
		// margin-top: -15px;
    	// margin-left: 210px;
		padding: 30px 15px;
		.t{
			font-size: 14px;
			color: #18191A;
			margin: 0 0px 20px 0;
			span{}
		}
	.file-container{
		margin-bottom: 20px;
		border-bottom: #F0F3F5 1px solid;
		.el-row{
			text-align: center;
			.el-col{
				.file-item{
					cursor: pointer;
					img{
						width: 130px;
						height: 148px;
						box-shadow: 0px 3px 10px 0px rgba(0, 0, 0, 0.2);
					}
					.name{
						margin: 0;
						font-size: 12px;
						color: #494b4d;
					}
					.scope{
						font-size: 12px;
					    // font-weight: bold;
					    background: #e8e7f4;
					    padding: 3px;
					    color: #9c8dc8;
					    border-radius: 3px;
					    position: absolute;
					    top: 10px;
					    right: 10px;
					}
				}
			}
		}
		.el-icon-document.attach{
			&:before{
				content: '';
				// background: url(../../assets/icons/task.pop.attached.png);
				width: 22px;
			    height: 23px;
			    position: absolute;
			    top: 40%;
			    left: 40%;
			}
			// zoom:3;
			color: #999;
			cursor: pointer;
		}
		.el-row{
			width: 102%;
		}
		.el-col{
			background-color: white;
			width: 240px;
		    height: 200px;
		    margin: 0 7px 7px 0;
		}
			.file-item{
				width: 100%;
			    height: 100%;
			    position: relative;
				.el-icon-document{
					zoom: 1;
					width: 88px;
					height: 88px;
					background-size: 100% auto;
				    background-repeat: no-repeat;
				    position: absolute;
				    top: 56px;
				    left: 17px;
					&:before{
						content: '';
					}
				}
				p{
				    position: absolute;
				    top: 50%;
				    transform: translateY(-50%);
				    left:116px;
				    right: 18px;
				    text-align: left;
					font-size: 12px;
					color: #1F1F1F;
				}
				em{
					font-style: normal;
					font-size: 11px;
					color: #939799;
					letter-spacing: .6px;
					right: 10px;
					bottom: 8px;
					position: absolute;
				}

			    &.stat_case {
			    	.el-icon-document{
				    	background-image: url(../../assets/stat_report/stat_case.gif);
				    }
				    p{
				    	&:after{
				    		content: '案件覆盖率情况统计表';
				    	}
				    }
			    }
			    &.hour {
			    	.el-icon-document{
			    		background-image: url(../../assets/stat_report/hour.gif);
			    	}
			    	p{
				    	&:after{
				    		content: '案件平均处理时效统计表';
				    	}
				    }
			    }
			    &.week_hour {
			    	.el-icon-document{
			    		background-image: url(../../assets/stat_report/week_hour.gif);
			    	}
			    	p{
				    	&:after{
				    		content: '周案件处理时效统计表';
				    	}
				    }
			    }
			    &.last_week_hour {
			    	.el-icon-document{
			    		background-image: url(../../assets/stat_report/last_week_hour.gif);
			    	}
			    	p{
				    	&:after{
				    		content: '周案件处理时效环比统计表';
				    	}
				    }
			    }
			    &.bill {
			    	.el-icon-document{
			    		background-image: url(../../assets/stat_report/bill.png);
			    	}
			    	p{
				    	&:after{
				    		white-space: nowrap;
				    		content: '案件回款情况统计表';
				    	}
				    }
			    }
			    &.null {
					.el-icon-document{
				    	background-image: url(../../assets/stat_report/null.gif);
					    filter:brightness(.98);
						width: 160px;
					    height: 120px;
					    left: 40px;
    					top: 35px;
    					&:after{
    						content: '本周无报表';
							font-size: 12px;
							color: #939799;
							position: absolute;
							bottom: -20px;
							left: 52px;
    					}
					}
			    }
			}
		}
	}
}
</style>
